<?php


namespace app\manage\controller;

use think\Db;
use think\Log;

class ClueLog extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function batchLog(){
        $list=Db::name('clue_progress')->alias('a')->field('a.id,b.clue_id')
            ->join('clue_log b','b.id=a.clue_log_id')
            ->select();
        foreach ($list as $v){
            Db::name('clue_progress')->where('id',$v['id'])->update(['clue_id'=>$v['clue_id']]);
        }
    }

    public function index()
    {
        // 查询条件start
        $clue_id = input('clue_id','');
        $clue_name = input('clue_name','');
        $phone = input('phone','');
        $times = input('times','');
        $sprovince = input('sprovince','');
        $scity = input('scity','');
        $mer_name = input('mer_name','');
        $ac_name = input('ac_name','');
        $adv_id = input('adv_id','');
        $mer_id = input('param.mer_id','');
        $pro_id = input('pro_id','');

        $map = [];
        if($clue_name != ''){
            $map['a.clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['a.phone'] = $phone;
        }
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }
        if($clue_id){
            $map['a.ad_clue_id']=$clue_id;
        }

        if($adv_id){
            $map['a.adv_id']=$adv_id;
        }

        if(!empty($sprovince)&&empty($scity)){
            $map['a.city']=['like',$sprovince.'-'.'%'];
        }

        if(!empty($sprovince)&&!empty($scity)){
            $map['a.city']=$sprovince.'-'.$scity;
        }

        if($mer_id){
            $map['a.mer_id']=$mer_id;
        }
        if($pro_id!=''){
            $map['a.pro_id']=$pro_id;
        }

        if(in_array($this->group_id,[4,5])){
            $map1['bind_aid|weihu_aid']=$this->uid;
//            $map1['status']=1;
            if(!empty($mer_name)){
                $mArr=model('merchant')->where($map1)->where('mer_name','like','%'.$mer_name.'%')->column('id');
            }else{
                $mArr=model('merchant')->where($map1)->column('id');
            }
            if($mArr){
                if(!in_array($mer_id,$mArr)){
                    $map['mer_id']=['in',$mArr];
                }else{
                    $map['mer_id']=$mer_id;
                }
            }else{
                $map['mer_id']=0;
            }
        }else{
            if(!empty($mer_name)){
                $merchant=model('Merchant')->where('mer_name','like','%'.$mer_name.'%')->column('id');
                if(!empty($merchant)){
                    $map['mer_id']=['in',$merchant];
                }else{
                    $map['mer_id']=0;
                }
            }
        }
        $listNull=false;
        if(!empty($ac_name)){
            $adv_idArr=model('Account')->where('acc_name','like','%'.$ac_name.'%')->column('adv_id');
            if(!empty($adv_id)){
                $map['adv_id']=['in',$adv_idArr];
            }else{
                $listNull=true;
            }
        }

        // 查询条件end

        if($listNull){
            $infos=[];
        }else{
            $infos = model('ClueLog')->alias('a')->field('a.*,b.type,b.remark,c.mer_name,c.username,c.phone mer_phone,c.mer_name,c.mer_desc')
                ->join('clue b','a.clue_id=b.id','LEFT')
                ->join('merchant c','a.mer_id=c.id','LEFT')
                ->where($map)
                ->order('a.id desc')
                ->paginate();
//                ->getInfosByMap($map, '', false);
        }

        $productAll =Db::name('product')->column('name','id');
        $products = model('Product')->where('status',1)->column('name','id');
        $channels = $this->getChannelArray();

        foreach ($infos as $k=>$v){
            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $prov = $this->getCityName($ids[0]);
                $city = $this->getCityName($ids[1]);
                if($prov == $city){
                    $infos[$k]['city'] = $prov;
                }else{
                    $infos[$k]['city'] = $prov.'-'.$city;
                }
            }


            $infos[$k]['telephone']=message_safe('Tel',$v['phone']);

//            $product = model('Product')->field('name')->where(['id'=>$v['pro_id']])->find();
//            $merchant = model('Merchant')->field('mer_name,username,phone,mer_desc')->where(['id'=>$v['mer_id']])->find();
            $account = model('Account')->field('channel_id,acc_name,acc_desc')->where(['adv_id'=>$v['adv_id']])->find();
            $infos[$k]['acc_name'] = $account['acc_name'] ?? "";
            $infos[$k]['acc_desc'] = $account['acc_desc'] ?? "";
            $infos[$k]['channel_name'] = $channels[$account['channel_id']] ?? "";
            $infos[$k]['pro_name'] = $productAll[$v['pro_id']];
//            $infos[$k]['mer_name'] = $merchant['mer_name'];
//            $infos[$k]['username'] = $merchant['username'];
//            $infos[$k]['mer_phone'] = $merchant['phone'];
//            $infos[$k]['mer_desc'] = $merchant['mer_desc'];
            $infos[$k]['charge_type'] = config('clue.charge_types')[$v['charge_type']];
            $infos[$k]['progress'] = model('ClueProgress')->where('clue_log_id',$v['id'])->order('id desc')->select();

            if(empty($v['remark'])){
                $infos[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if($kk=='城市'){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if($vv['name']=='城市'){
                                }else{
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $infos[$k]['remark_data']=$remarkArr;
            }

        }
        $province = Db::name('city')->where(['pid'=>1])->select();
        return $this->fetch('',[
            'infos' => $infos,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'times' => $times,
            'clue_id' => $clue_id,
            'sprovince' => $sprovince,
            'scity' => $scity,
            'province' => $province,
            'mer_name' => $mer_name,
            'ac_name' => $ac_name,
            'adv_id' => $adv_id,
            'group_id' => $this->group_id,
            'pro_id' => $pro_id,
            'products' => $products,
        ]);
    }

    //线索
    public function progressLog()
    {
        // 查询条件start
        $clue_id = input('clue_id','');

        $map['clue_log_id']=$clue_id;

        // 查询条件end

        $infos = model('ClueProgress')->where($map)->select();

//        foreach ($infos as $k=>$v){
//            if($v['city'] != ''){
//                $ids = explode('-',$v['city']);
//                $prov = $this->getCityName($ids[0]);
//                $city = $this->getCityName($ids[1]);
//                if($prov == $city){
//                    $infos[$k]['city'] = $prov;
//                }else{
//                    $infos[$k]['city'] = $prov.'-'.$city;
//                }
//            }
//
//            $product = model('Product')->field('name')->where(['id'=>$v['pro_id']])->find();
//            $merchant = model('Merchant')->field('mer_name,username,phone,mer_desc')->where(['id'=>$v['mer_id']])->find();
//            $account = model('Account')->field('acc_name,acc_desc')->where(['adv_id'=>$v['adv_id']])->find();
//            $infos[$k]['acc_name'] = $account['acc_name'];
//            $infos[$k]['acc_desc'] = $account['acc_desc'];
//            $infos[$k]['pro_name'] = $product['name'];
//            $infos[$k]['mer_name'] = $merchant['mer_name'];
//            $infos[$k]['username'] = $merchant['username'];
//            $infos[$k]['mer_phone'] = $merchant['phone'];
//            $infos[$k]['mer_desc'] = $merchant['mer_desc'];
//            $infos[$k]['charge_type'] = config('clue.charge_types')[$v['charge_type']];
//        }

        return $this->fetch('',[
            'infos' => $infos,
        ]);
    }

    /**
     * 软删除
     */
    public function delete2()
    {
        $bool=$this->tokenBucket($this->uid,'adminDel',5,1);
        if(!$bool){
            return $this->showReturnCode(1009,'请勿频繁操作');
        }
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();
            $infoTemp = model($model)->getInfoByMap('','','',false);
            if(isset($infoTemp['parent_id'])){
                $infosCount = model($model)->countNum(['parent_id'=>$id],false); // 查询子分类数量
                if($infosCount > 0)  return $this->showReturnCode(1009,'该分类下有子分类,请批量删除');
            }
            $info=model($model)->find($id);
            $res = model($model)->destroy($id);
            if($res){
                if(!empty($info)&&$info['price']>0){
                    Db::name('merchant')->where('id',$info['mer_id'])->setInc('balance',$info['price']);
                }
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    //重复线索统计
    public function clueStatistics()
    {
        // 查询条件start

        $type = input('type',1);
        $num = input('num',2);
        $times = input('times','');
        if($num<2){
            $num=2;
        }
        if($type==1){
            $groupBy='phone';
        }else{
            $groupBy='city,clue_name';
        }
        $clue_name = input('clue_name','');
        $phone = input('phone','');

        $map = [];

        if($clue_name != ''){
            $map['clue_name'] = ['like','%'.$clue_name.'%'];
        }
        if($phone != 0){
            $map['phone'] = $phone;
        }
        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
        }


        $infos = model('Clue')->field('*,count(id) cnum')->where($map)->order('id desc')->group($groupBy)->having('cnum >'.$num)->select();

//        dump($infos);die;

        $channels = $this->getChannelArray();
//        $products = model('Product')->getListByMap();
        $productAll =Db::name('product')->column('name','id');


        foreach ($infos as $k=>$v){

            $infos[$k]['product_name']=empty($v['pro_id'])?'未知':$productAll[$v['pro_id']];
            $infos[$k]['cityid']=$v['city'];

            if($v['city'] != ''){
                $ids = explode('-',$v['city']);
                $cityNum=count($ids);
                if($cityNum==1){
                    $infos[$k]['city'] = $this->getCityName($ids[0]);
                }elseif ($cityNum==2){
                    $prov = $this->getCityName($ids[0]);
                    $city = $this->getCityName($ids[1]);
                    if($prov == $city){
                        $infos[$k]['city'] = $prov;
                    }else{
                        $infos[$k]['city'] = $prov.'-'.$city;
                    }
                }
            }
            if($v['push_time']){
                $infos[$k]['push_time'] = date('Y-m-d H:i:s',$v['push_time']);
            }

            $infos[$k]['acc_name'] = '手动添加的线索';
            $infos[$k]['acc_desc'] = '手动添加';
            $infos[$k]['channel_name'] = '后台系统';
            if($v['adv_id'] != ''){
                $account = Db::name('account')->where('adv_id','=',$v['adv_id'])->find();
                if($account){
                    $infos[$k]['acc_name'] = $account['acc_name'];
                    $infos[$k]['acc_desc'] = $account['acc_desc'];
                    $infos[$k]['channel_name'] = $channels[$account['channel_id']];
                }else{
                    $infos[$k]['acc_name'] = '未知账号';
                    $infos[$k]['acc_desc'] = '';
                    $infos[$k]['channel_name'] = $channels[$v['type']];
                }
            }
            if(empty($v['remark'])){
                $infos[$k]['remark_data']=[];
            }else{
                $remark=json_decode($v['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if($kk=='城市'){
                            }else{
                                $remarkArr[]=$kk.'：'.$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($v['type']==1){
                                if($vv['name']=='城市'){
                                }else{
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    $remarkArr[]=$vv['name'].'：'.$vv['value'];
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr=[];
                    $remarkArr[]=$v['remark'];

                }
                $infos[$k]['remark_data']=$remarkArr;
            }

        }

//        $sources = Db::name('clue')->field('source')->where('source','<>','')->group('source')->select();

//        $this->assign('province',$province);
//        dump($infos);die;

        return $this->fetch('',[
            'infos' => $infos,
            'clue_name' => $clue_name,
            'phone' => $phone,
            'times' => $times,
            'type' => $type,
            'num' => $num,

        ]);
    }

}